package com.project.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.project.bean.CustomerBean;
import com.project.bean.GradeBean;
import com.project.bean.RoleBean;
import com.project.mapper.IGradeMapper;
import com.project.mapper.IRoleMapper;
import com.project.service.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Service
@Transactional
public class RoleServiceImp implements IRoleService {
    @Autowired
    private IRoleMapper roleMapper;
    @Autowired
    private IGradeMapper gradeMapper;
    @Override
    public IPage<RoleBean> findByItem(Integer pageNo) {
        QueryWrapper<RoleBean> query = new QueryWrapper<RoleBean>();
        return roleMapper.selectPage(new Page<RoleBean>(pageNo,3),query);
    }

    @Override
    public void delRole(Integer roleId) {
        roleMapper.delRole(roleId);
    }

    @Override
    public void addRole(RoleBean roleBean, Integer[] gradeIds) {
        RoleBean roleBean1 =roleMapper.selectOne(new QueryWrapper<RoleBean>().eq("r_name",roleBean.getRoleName()));
        if (gradeIds!= null && gradeIds.length > 0 && roleBean1 == null) {
            List<GradeBean> grades = new ArrayList<>();
            for (Integer gradeId : gradeIds) {
                QueryWrapper<GradeBean> qw = new QueryWrapper<GradeBean>();
                qw.eq("pk_gradeId",gradeId);
                GradeBean grade = gradeMapper.selectOne(qw);
                grades.add(grade);
            }
            roleBean.setGradeList(grades);
            roleMapper.insert(roleBean);
            roleMapper.addRoleGradeByRoleId(roleBean.getRoleId(),gradeIds);
        }
    }

    @Override
    public RoleBean findRoleByRoleName(String roleName) {
        return roleMapper.selectOne(new QueryWrapper<RoleBean>().eq("r_name",roleName));
    }

    @Override
    public RoleBean findById(Integer roleId) {
        RoleBean roleBean = roleMapper.selectById(roleId);
        List<GradeBean> gradeBeanList=roleMapper.findByRoleId(roleId);
        roleBean.setGradeList(gradeBeanList);
        return roleBean;
    }

    @Override
    public List<RoleBean> findAll() {
        return roleMapper.selectList(null);
    }

    @Override
    public void updateRoleGradeById(Integer roleId, Integer[] gradeIds) {
        if (gradeIds != null && gradeIds.length!=0 && roleId != 0) {
            //先通过用户id删除角色表相关信息，再添加新的权限信息
            roleMapper.delRoleGradeByRoleId(roleId);
            roleMapper.addRoleGradeByRoleId(roleId, gradeIds);
        }

    }
}
